//
//  ZuoJHomeController.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/7/28.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SDWebImage
class ZuoJHomeController: ZuoJBaseController {
    
    var statues: [Status]? {
        didSet {
            
            tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !UserAccount.userLogon {
            
            visitorView?.setupInfoView(true, message: "关注一些人，回这里看看有什么惊喜", imageName: "visitordiscover_feed_image_house")
            //MARK :::切记不要手滑，忘了写return
            //强制解包，不返回，报错解包了一个optional的值
            return
            
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedCellPhoto:", name: ZuoJStatusPictureViewSelectedNotification, object: nil)
        prepareView()
        loadData()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func selectedCellPhoto(n: NSNotification) {
        
        print("监听到了")
        guard let urls = n.userInfo?[ZuoJStatusPictureViewSelectedURLsKey] as? [NSURL] else {
            
            print("没有URL数据")
            return
        }
        guard let index = n.userInfo?[ZuoJStatusPictureViewSelectedIndexKey] as? NSIndexPath else {
            print("没有索引")
            return
        }
        
        guard let picView = n.object as? StatusPictureView else {
            
            print("图像视图不存在")
            return
        }
        
        presentView = picView
        presentIndexPath = index
        presentIconView.sd_setImageWithURL(urls[index.item])
        
        
        
        let vc = PhotoBrowserViewController(urls: urls, selectedIndex: index.item)
        
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
        
    }
    private func prepareView() {
        
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier:StatusCellIdentifier.NormalCell.rawValue)
        
        //行高
        tableView.estimatedRowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        refreshControl = ZuoJRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
    }
    
    //上拉刷新标志
    private var pullupRefreshFlag = false
    
    func loadData() {
        
        refreshControl?.beginRefreshing()
        
        var since_id = statues?.first?.id ?? 0
        var max_id = 0
        
        if pullupRefreshFlag {
            since_id = 0
            max_id = statues?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (datalist, error) -> () in
            
            self.refreshControl?.endRefreshing()
            self.pullupRefreshFlag = false
            if error != nil {
                print(error)
                return
            }
            
            let count = datalist?.count ?? 0
            if since_id > 0 {
                
                self.showPulldownTip(count)
            }
            
            print("刷新到\(count)条数据")
            
            if count == 0 {
                return
            }
            if since_id > 0 {
                
                self.statues = datalist! + self.statues!
            }else if max_id > 0 {
                
                self.statues = self.statues! + datalist!
                
                
            }else {
                
                self.statues = datalist
            }
            
            
        }
    }
    
    private func showPulldownTip(count:Int) {
        
        if tipLabel.layer.animationForKey("position") != nil {
            
            return
        }
        
        tipLabel.text = (count == 0) ? "暂时没有新   微博" : "\(count)条新微博"
        
        let rect = tipLabel.frame
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            }) { (_) -> Void in
                self.tipLabel.frame = rect
        }
    }
    
    //MRAK -- 数据源方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statues?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statues![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusCell
        
        //判断indexpath的值
        if indexPath.row == statues!.count - 1 {
            pullupRefreshFlag = true
            loadData()
        }
        
        cell.status = statues![indexPath.row]
        return  cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statues![indexPath.row]
        if let h = status.rowHeight {
            return h
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status)) as? StatusCell
        
        status.rowHeight = cell!.rowHeight(status)
        return status.rowHeight!
    }
    
    private lazy var tipLabel: UILabel = {
        
        let h:CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height: h))
        
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(label,atIndex:0)
        
        
        return label
        }()
    
    private var isPresented = false
    private lazy var presentIconView:UIImageView = {
        
        let iv = UIImageView()
        iv.contentMode  = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
        
    }()
    private var presentView:StatusPictureView?
    private var presentIndexPath: NSIndexPath?
}
extension ZuoJHomeController: UIViewControllerTransitioningDelegate {
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
         isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    
}
extension ZuoJHomeController: UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 2.0
    }
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        
        if isPresented {
            
         let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            
            transitionContext.containerView()?.addSubview(presentIconView)

            let fromRect = presentView!.cellScreenRect(presentIndexPath!)
            let toRect = presentView!.cellFullScreenRect(presentIndexPath!)
            
            presentIconView.frame = fromRect
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
   
                self.presentIconView.frame = toRect
            
            } , completion:{ _ in
                
                self.presentIconView.removeFromSuperview()
                transitionContext.containerView()?.addSubview(toView)
                transitionContext.completeTransition(true)
        })

            return
        }
        
           let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
           let indexPath = fromVC.currentImageIndex()
           let rect = presentView!.cellScreenRect(indexPath)
           let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
           let iv = fromVC.currentImageView()
           iv.center = fromView.center
        
           let scale = fromView.transform.a
           iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
           transitionContext.containerView()?.addSubview(iv)
           fromView.removeFromSuperview()
        
           UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            
            
                iv.frame = rect
            
                }, completion: { _ in
                    
                    iv.removeFromSuperview()
                    
                    transitionContext.completeTransition(true)
            })
        }
    }
